import axios from 'axios';
import wx from 'weixin-js-sdk';

var shareInfo = (function (mod) {
  function identify(URL) {
    var requestUrl = URL.match('m.nbd.com.cn') ? 'https://m.nbd.com.cn/get_wechat_signature' : 'http://www.nbd.com.cn/get_wechat_signature';

    axios({
      method: 'post',
      url: requestUrl,
      data: { share_url: URL }
    }).then(res => {
      let { data } = res;

      wx.config({
        debug: false,
        appId: data.data.appid,
        timestamp: data.data.timestamp,
        nonceStr: data.data.noncestr,
        signature: data.data.signature,
        jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareQZone', 'updateAppMessageShareData', 'updateTimelineShareData']
      });
    });
  }
  /**
   * [init description]
   * @author mao
   * @version 1
   * @date    2017-06-06
   * @param   {object}   options 穿入参数
   * img, title, desc, shareURL
   */
  mod.init = function (options) {
    //认证
    identify(location.href);
    wx.ready(function () {
      const imageurl = options.img;
      const title = options.title;
      const desc = options.desc;
      const link = options.shareURL;
      // 分享到朋友圈”及“分享到QQ空间”
      wx.updateTimelineShareData({
        title: title, // 分享标题
        link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: imageurl, // 分享图标
        success: function (res) {
          // 设置成功
          // console.log("分享成功返回的信息为:", res);
        }
      });

      // “分享给朋友”及“分享到QQ”
      wx.updateAppMessageShareData({
        title: title, // 分享标题
        desc: desc, // 分享描述
        link: link, // 分享链接
        imgUrl: imageurl, // 分享图标
        success: function (res) {
          // console.log("分享成功返回的信息为:", res);;
        }
      });
      wx.onMenuShareTimeline({
        title: title,
        desc: desc,
        link: link,
        imgUrl: imageurl,
        success: function () {},
        cancel: function () {}
      });

      wx.onMenuShareAppMessage({
        title: title,
        desc: desc,
        link: link,
        imgUrl: imageurl,
        success: function () {},
        cancel: function () {}
      });

      wx.onMenuShareQQ({
        title: title,
        desc: desc,
        link: link,
        imgUrl: imageurl,
        success: function () {},
        cancel: function () {}
      });

      wx.onMenuShareQZone({
        title: title,
        desc: desc,
        link: link,
        imgUrl: imageurl,
        success: function () {},
        cancel: function () {}
      });
    });

    wx.error(function (res) {
      console.log(res);
    });
  };

  return mod;
})(shareInfo || {});

export default shareInfo;
